package com.hyk.commonLib.common.utils;

import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * Created by 贺玉琨 on 2019/3/7 0007.
 */
public class EncodeUtils {
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte aByte : bytes) {
            sb.append(HEX_DIGITS[(aByte & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[aByte & 0x0f]);
        }
        return sb.toString();
    }

    public static byte[] base64Encode(String str) {
        return Base64.encode(str.getBytes(), Base64.DEFAULT);
    }

    public static String base64EncodeToString(String str) {
        return Base64.encodeToString(str.getBytes(), Base64.DEFAULT).replace("\n", "");
    }

    public static byte[] base64Decode(String str) {
        return Base64.decode(str, Base64.DEFAULT);
    }

    public static String base64DecodeToString(String str) {
        return new String(Base64.decode(str, Base64.DEFAULT));
    }

    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String urlDecode(String str) {
        try {
            return URLDecoder.decode(str, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
